import { InputItem, TextareaItem, DatePicker, List, Picker } from 'antd-mobile';
import { createForm } from 'rc-form';
import { Component } from 'react'
class StandardForm extends Component {
  constructor(props) {
    super(props)
    this.getFieldsValue = this.getFieldsValue.bind(this)
    this.validateFields = this.validateFields.bind(this)
    this.setFieldsValue = this.setFieldsValue.bind(this)
    this.getFieldValue = this.getFieldValue.bind(this)
  }
  state = {
    error: {}
  }
  setFieldsValue(fieldsValue) {
    this.props.form.setFieldsValue(fieldsValue)
  }
  getFieldsValue(names){
    const { form } = this.props
    return form.getFieldsValue(names)
  }
  getFieldValue(name) {
    const { form } = this.props
    return form.getFieldValue(name)
  }
  validateFields(cb) {
    const { form } = this.props
    form.validateFields((error, values) => {
      this.setState({error: error || {} })
      cb(error, values)
    })
  }
  render() {
    const { form, formItems, labelSuffix = ':' } = this.props
    const { getFieldProps } = form
    return formItems.map((item, idx )=> {
      if(item.render) {
        return item.render(item, form)
      } else if(item.type === 'Picker') {
        let data = null
        if(item.data.toString() === '[object Object]') {
          data = Object.entries(item.data).map(([key, val]) => {
            return {
              value: +key,
              label: val
            }
          })
        }
        return <Picker
          key={`${item.name}${idx}`}
          data={data}
          {...item.layoutOption}
          {...getFieldProps(item.name, item.options)}
          // onChange={this.onChangeColor}
        >
          <List.Item arrow="horizontal">{item.label}{labelSuffix}</List.Item>
        </Picker>
      } else if(item.type === 'TextareaItem') {
        return <TextareaItem
          title={`${item.label}${labelSuffix}`}
          error={this.state.error[item.name]}
          key={`${item.name}${idx}`}
          placeholder={item.placeholder || '请输入'}
          {...item.layoutOption}
          {...getFieldProps(item.name, item.options)}
        />
      } else if(item.type === 'DatePicker') {
        return <DatePicker
          {...item.layoutOption}
          error={this.state.error[item.name]}
          key={`${item.name}${idx}`}
          {...getFieldProps(item.name, item.options)}
          title={item.label}
          extra={item.placeholder}
        >
          <List.Item arrow="horizontal">{item.label}{labelSuffix}</List.Item>
        </DatePicker>
      } else {
        return <InputItem
          {...item.layoutOption}
          {...getFieldProps(item.name, item.options)}
          error={this.state.error[item.name]}
          key={`${item.name}${idx}`}
          placeholder={item.placeholder || '请输入'}
        >{item.label}{labelSuffix}</InputItem>

      }
    }) 
  }
}
export default createForm()(StandardForm)